SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO


CREATE PROCEDURE dbo.DnnProduct_GetScheduleNextTask
	@Server varchar(150)
AS
	SELECT TOP 1 S.*, 
		   SH.NextStart
	FROM dbo.DnnProduct_Schedule S
		LEFT JOIN dbo.DnnProduct_ScheduleHistory SH ON S.ScheduleID = SH.ScheduleID
	WHERE ((SH.ScheduleHistoryID = (SELECT TOP 1 S1.ScheduleHistoryID FROM dbo.DnnProduct_ScheduleHistory S1 
										WHERE S1.ScheduleID = S.ScheduleID 
										ORDER BY S1.NextStart DESC) 
									OR SH.ScheduleHistoryID IS NULL) 
				AND S.Enabled = 1) 
		AND (S.Servers LIKE ',%' + @Server + '%,' or S.Servers IS NULL)
	ORDER BY SH.NextStart ASC
GO
